/**
 *内容管理 - 链接管理
 * create by xiaomin on 3/07/2018
 */
import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'dva'
import {Page} from 'components'
import {routerRedux} from 'dva/router'
import {Row, Col, Button, Popconfirm, Tabs} from 'antd'
import queryString from 'query-string'


import LinkTable from './components/LinkTable'
import LinkPubTable from './components/LinkPubTable'
import LinkFilter from './components/LinkFilter'
import LinkPubFilter from './components/LinkPubFilter'
import LinkModal from './components/LinkModal'
import LinkPubModal from './components/LinkPubModel'

import style from './link.less'


const ContentLink = ({
                       location, dispatch, contentLink, loading,
                     }) => {

  const {query, pathname} = location
  const {
    modalPubTreeData,
    modalPubTreeDataPgPletId,
    list2,
    list,
    selectedRowKeys,
    selectedRowKeysPub,

    isMotion,
    modalVisible,
    PubmodalVisible,
    modalType,
    currentItem,
    pagination,
    isPubModal,
    editContentId,
    editInitialContent,
    editContentFormat,
    editHtmlContent,
    editEditorInstance,
    switchLinkPubFilterType,
  } = contentLink
  //刷新
  const handleRefresh = (newQuery) => {
    dispatch(routerRedux.push({
      pathname,
      search: queryString.stringify({
        ...query,
        ...newQuery,
      }),
    }))
  }
  const handleRefresh2 = (newQuery) => {
    let linkPubFilterType = window.localStorage.getItem("linkPubFilterType")
    newQuery.linkPubFilterType = linkPubFilterType
    dispatch({
      type: 'contentLink/getLinkPubModel',
      payload: {...newQuery},
    })
  }
  //编辑
  const editorProps = {
    editContentId,
    editInitialContent,
    editContentFormat,
    editHtmlContent,
    editEditorInstance,
    // 内容改变
    onHTMLChange: (htmlContent) => {
      console.log(htmlContent)
      dispatch({
        type: 'contentLink/editorContentUpdate',
        payload: {
          editHtmlContent: htmlContent,
        },
      })
    },
  }
  // 创建、编辑 模态
  const modalProps = {
    item: modalType === 'create' ? {} : currentItem,
    // editorItem: currentItem["content"] || '',
    visible: modalVisible,
    maskClosable: false,
    confirmLoading: loading.effects[`contentLink/${modalType}`],
    title: `${modalType === 'create' ? '新建链接' : '编辑链接'}`,
    okText: "确认",
    cancelText: "取消",
    // wrapClassName: 'vertical-center-modal',
    wrapClassName: style["link-editor-modal"],
    onOk (data) {
      data.content = editHtmlContent
      dispatch({
        type: `contentLink/${modalType}`,
        payload: data,
      })
        .then(() => {
          handleRefresh()
        })
    },
    onCancel () {
      dispatch({
        type: 'contentLink/hideModal',
      })
    },
    editorProps: editorProps,

  }

  // 发布模态
  const modalPubProps = {
    visible: PubmodalVisible,
    modalPubTreeData: modalPubTreeData,
    modalPubTreeDataPgPletId: modalPubTreeDataPgPletId,
    maskClosable: false,
    // loading: loading.effects[`contentArticle/getPubTargetModel`],
    // confirmLoading: loading.effects[`contentLink/addPub}`],
    title: '选择要发布对象及频道',
    okText: "确认",
    cancelText: "取消",
    destroyOnClose: true,
    wrapClassName: style["link-pub-modal"],
    onOk (data) {
      data.linkId = selectedRowKeys
      dispatch({
        type: `contentLink/insertPubLinkModel`,
        payload: data,
        // payload: {
        //   portletId: modalPubTreeData[1],
        //   linkId: selectedRowKeys.join(','),
        // },
      })
        .then(() => {
          handleRefresh()
        })
    },
    onCancel () {
      dispatch({
        type: 'contentLink/hidePubModal',
      })
    },
    onCheck (checkedKeys) {
      console.log(checkedKeys)
      dispatch({
        type: 'contentArticle/showPubModal',
        payload: {
          modalPubTreeData: checkedKeys,
        },
      })
    },
    // 根据发布对象获取发布位置
    handleRadioChange (e) {
      dispatch({
        type: 'contentLink/getPubTargetModel',
        payload: {
          toWho: e.target.value,
        },
      })
    },
    // 获取发布频道
    handlePgPletIdGet () {
      dispatch({
        type: 'contentLink/getPgPletId',
      })
    },

  }

  //top 功能键
  const filterProps = {
    isMotion,
    filter: {
      ...query,
    },
    onFilterChange (value) {
      handleRefresh({
        ...value,
        page: 1,
      })
    },
    onAdd () {
      dispatch({
        type: 'contentLink/showModal',
        payload: {
          modalType: 'create',
          currentItem: {}, // 新建时清空数据
        },
      })
    },
    switchIsMotion () {
      dispatch({type: 'contentLink/switchIsMotion'})
    },
  }

  //top 发布功能键
  const PubfilterProps = {
    isMotion,
    selectedRowKeysPub, // 选中行数
    filter: {
      ...query,
    },
    onFilterChange (value) {
      handleRefresh2({
        ...value,
        page: 1,
      })
    },
    // switchLinkPubFilter (type) {
    //   dispatch({
    //     type: 'contentLink/switchLinkPubFilter',
    //     payload: {
    //       switchLinkPubFilterType: type,
    //     },
    //   })
    // },
  }

  //table
  const listProps = {
    isPubModal,
    dataSource: list,
    loading: loading.effects['contentLink/query'],
    pagination,
    // 删除
    onDeleteItem (id) {
      dispatch({
        type: 'contentLink/delete',
        payload: id,
      })
        .then(() => {
          handleRefresh({
            page: (list.length === 1 && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
        })
    },
    // 编辑
    onEditItem (item) {
      dispatch({
        type: 'contentLink/showModal',
        payload: {
          modalType: 'update',
          currentItem: item,
        },
      })
    },
    rowSelection: {
      selectedRowKeys,
      onChange: (keys) => {
        dispatch({
          type: 'contentLink/updateState',
          payload: {
            selectedRowKeys: keys,
          },
        })
      },
    },
  }

  const listProps2 = {
    isPubModal,
    dataSource: list2,
    loading: loading.effects['contentLink/getLinkPubModel'],
    pagination,
    location,
    isMotion,
    onChange (page) {
      handleRefresh({
        page: page.current,
        pageSize: page.pageSize,
      })
    },
    // 删除
    onDeleteItemPub (data) {
      // 删除时加入类型判断，区分删除的链接属于单位或角色
      data.linkPubFilterType = window.localStorage.getItem("linkPubFilterType")
      dispatch({
        type: 'contentLink/deletePub',
        payload: data,
      })
        .then(() => {
          handleRefresh2({
            page: (list2.length === 1 && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
        })
    },
    // 编辑
    // onEditItem (item) {
    //   dispatch({
    //     type: 'contentLink/showModal',
    //     payload: {
    //       modalType: 'update',
    //       currentItem: item,
    //     },
    //   })
    // },
    rowSelection: {
      selectedRowKeysPub,
      onChange: (keys) => {
        dispatch({
          type: 'contentLink/updateState',
          payload: {
            selectedRowKeysPub: keys,
          },
        })
      },
    },
  }

  // 发布，默认角色发布
  const onPub = () => {
    dispatch({
      type: 'contentLink/getPgPletId',
    })
  }

  //多选删除
  const handleDeleteItems = () => {
    dispatch({
      type: 'contentLink/multiDelete',
      payload: {
        ids: selectedRowKeys,
      },
    })
      .then(() => {
        handleRefresh({
          page: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
        })
      })
  }

  const handleTabsChange = (activeKey) => {
    if (activeKey === '1') {
      dispatch({
        type: 'contentLink/query',
      })
    } else if (activeKey === '2') {
      // 首次进入发布链接页，默认 region
      window.localStorage.setItem("linkPubFilterType", "region")
      dispatch({
        type: 'contentLink/getLinkPubModel',
      })
    }
  }

  return (
    <Page inner>

      <Tabs type="card" onChange={activeKey => handleTabsChange(activeKey)}>
        <Tabs.TabPane tab="已录入的链接" key="1">
          {/*头部功能键*/}
          <LinkFilter {...filterProps}  />
          {/*临时按钮，选中数量大于0时，右上角显示常用按钮*/}
          {
            selectedRowKeys.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              <Col>
                {`选中 ${selectedRowKeys.length} 项 `}
                <Button type="primary" style={{marginLeft: 8}} onClick={onPub}>发布</Button>
                <Popconfirm title="是否确认删除？" placement="left" onConfirm={handleDeleteItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }

          {/*表格*/}
          <LinkTable {...listProps} />
          {/*弹出层，包括创建、修改*/}
          {modalVisible && <LinkModal {...modalProps}  />}
          {/*弹出层，发布*/}
          {PubmodalVisible && <LinkPubModal {...modalPubProps}  />}

        </Tabs.TabPane>
        <Tabs.TabPane tab="已发布的链接" key="2">
          {/*头部功能键*/}
          <LinkPubFilter {...PubfilterProps}  />
          {/*临时按钮，选中数量大于0时，右上角显示常用按钮*/}
          {
            selectedRowKeysPub.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              <Col>
                {`选中 ${selectedRowKeysPub.length} 项 `}
                <Popconfirm title="是否确认删除？" placement="left" onConfirm={handleDeleteItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }
          {/*表格*/}
          <LinkPubTable  {...listProps2} />
        </Tabs.TabPane>
      </Tabs>


    </Page>
  )
}

ContentLink.propTypes = {
  contentLink: PropTypes.object,
  dispatch: PropTypes.func,
  location: PropTypes.object,
  loading: PropTypes.object,
}

export default connect(({contentLink, loading}) => ({contentLink, loading}))(ContentLink)














